var productView = null;
$(function() {	
	Backbone.sync = function (method, model, options) {	 		
	};	
	 _.templateSettings = {
		       interpolate : /\{\{(.+?)\}\}/g
   };
	 
var Product = Backbone.Model.extend({
	defaults:{		
		sel : false,
		productCount : 0
	},	
	initialize: function(item){		
		 this.bind('change:sel', this.selChanged, this);
		 this.bind('change:productCount', this.countChanged, this);
	},		
	save : function(){		
	},
	clear : function() {
		this.destroy();
	},	
	selChanged: function(){
		ChooseGoods(this.toJSON());
	},
	countChanged: function(){				
		var count = this.get("productCount");
		if (count < 1){
			this.set("sel", false);
		}		
		if (count >= 1){
			this.set("sel", true);
		}
		ChooseGoods(this.toJSON());
	},
    toggle: function() {
      this.checked(!this.get("sel"));
    },    
    checked: function(checked){
    	this.set("sel", checked);
        var sel = checked;
  		var productCount = this.get("productCount");
  		if (sel){		
  			if (productCount < 1) this.set("productCount", 1 );			
  		}
  		else{
  			if (productCount > 0) this.set("productCount", 0);
  			
  		}     		
    },
    validate: function(attrs, options){    	
    	if (attrs.productCount < 0){
    		return "count";
    	}
    },	
});	


var ProductList = Backbone.Collection.extend({		
	model: Product,
	save : function(){		
	},
	sels: function() {
	      return this.where({sel: true});
	}
});

products = new ProductList;

var ItemView = Backbone.View.extend({		
	tagName: "tr",		
	template : $('#product_template').html(),	
	template_buy : $('#product_template_buy').html(),	
	initialize : function(){	
	   this.model.bind('destroy', this.remove, this); 
	   this.model.bind('change', this.render, this);
	},
	events:{		
		"click .del"    : "delProduct",
		"click input[selable='1']" :  "toggleSel",
		"click .clickable" : "toggleSel",
		"click .NumMinus" : "NumMinus",
		"click .NumPlus" : "NumPlus",
		"change input[name='TxgoodsNum']" : "changeNum",
	},	
	//点击一行进行选择
	toggleSel: function(){			
		this.model.toggle();		
		
	},
	//减少
	NumMinus: function() {		
		var count = this.model.get("productCount");
		this.model.set("productCount", count-1, {validate:true});	 	    
	},
	//增加
	NumPlus : function(pid) {
		var count = this.model.get("productCount");
		this.model.set("productCount", count+1,{validate:true});	
	},
	
	changeNum: function(){
		var count = this.$("input[name='TxgoodsNum']").val();
		this.model.set("productCount", count, {validate:true});
		console.log(count)
	},
	delProduct : function(event){	
		var model = this.model;
		parent.$.messager.confirm('系统提示', '是否删除选中的数据？', function (r) {
			if (r) {					
			      $.getJSON("/ProductInfo/Delete",{id: model.get("productId")}, function(o){
			      	if (o.IsSuccess == false){
			      	   Dialog.alert(o.Message);
			      	}
		      		else{
		      			model.destroy();	
		      		}
		      	});      		
		    }
		});			
	},	
	render:function(){		
		var template_sel = null;
		var BusiAction = request("BusiAction");
		if (!BusiAction) template_sel = this.template;		
		else template_sel = this.template_buy;	
		
		var	template = _.template(template_sel, this.model.toJSON());				
		$(this.el).html(template);		
		return this;
	}
});

var ProductView = Backbone.View.extend({
	el : $('body'),
	initialize : function(){	
		 $.each(productData, function(i, item){					
		     var product  = new Product(item);					   
		     products.add(product);					    
		   });	
    	   this.render();
		       		 
	},	
	events:{
		"click input[name='selectall']" : "selectall",
		"click #delSel" : "delSels"
	},
	
	toggleSel: function(){
		this.model.toggle();		
		ChooseGoods(this.model.toJson());
	},
	render : function(){				
		for(var i = 0; i < products.length; i++){
			var product = products.at(i);
			product.set("index", i+1);
			this.addOne(product);
		}
	},
	
	selectall: function(){	
		var check = (this.$("input[name='selectall']").attr("checked") == "checked");
		for(var i = 0; i < products.length; i++){
			var product = products.at(i);
			product.checked(check);			
		}	
	},
	
	//添加一个任务到页面id为todo-list的div/ul中
	addOne: function(product){			
		var view = new ItemView({model : product});			
		this.$("#resultTable").append(view.render().el);		
	},		
	clearOne: function(product){		
		product.destroy();
	},
	
	clearAll : function(){	
		var length = products.length;
		for(var i = length-1; i >= 0; i--){
			var product = products.at(i);			
			product.destroy();			
		}			
	},
	
	allAll:function(){
		products.each(this.addOne);
	},	
	
	delSels: function(){
	  var ids = [];
	  var sels = products.sels();	 
	  sels.forEach(function(sel){
		  ids.push(sel.get("productId"));
	  });
	  
	  if (ids.length == 0) {
	        Dialog.alert("至少选中一条记录");
	        return;
	  }
		   
	parent.$.messager.confirm('系统提示', '是否删除选中的数据？', function (r) {
		if (r) {					 
	      $.getJSON("/ProductInfo/Delete",{ids: JSON.stringify(ids)}, function(o){
	      	if (o.IsSuccess == false){
	      	   Dialog.alert(o.Message);
	      	}
      		else{
      			_.invoke(sels, 'destroy');      		
      		}
	      });      		
		}
	});			
}
});		

   productView = new ProductView;
});

function delSels() {		
	productView.delSels();
}
function loadData(pageNo){
	productView.clearAll();
	productView.loadData(pageNo);
}

function queryData(keyWord){
	var keyWord = this.$("#SearchKeyWord").val();		
	productView.clearAll();
	productView.loadData(1, keyWord);
}

function loadDataWithClass(){
	productView.clearAll();	
	productView.loadData(1)
}
